<?php

/**
 * 通用类库
 * @author 咸洪伟
 * @version 0.0
 * @package njsystem
 * @subpackage application/libraries
 */
class Common
{

	private $_CI;
	
	public  $lang = array(//脚本语言
            'send_email'      => "您此次登陆的动态密码是#0",//登陆发送短息的提醒语
			'send_sms'      => "您此次登陆的动态密码是#0",//登陆发送短息的提醒语
			'doc_send_sms'  => "#0给你发送了一份关于#1的#2,注意进行查看",//收发文发送短息的提醒语,
			'doc_send_email'=> "#0给你发送了一份关于#1的#2,注意进行查看",//收发文发送短息的提醒语,
	);	
	
	private $_site_path ;
	function __construct() {
		$this->_CI = & get_instance();
		$this->_site_path = config_item( 'site_path' );
	}

	/**
	 * 回收站工具条
	 * @param string $model 模型名称
	 * @param unknown_type $pid
	 */
	public function get_recycled( $model, $recycled, $action = "index" ) {
		$data = array(
			'model' => $model,
			'recycled' => $recycled,
			'action' => $action,
		);
		$str = $this->_CI->load->view_part( $this->_site_path.'/site/recycled', $data );
	}

	/**
	 * 回收站 时的列表操作按钮
	 * @param string $model 模型名称
	 * @param unknown_type $pid
	 */
	public function get_recycled_button( $model, $recycled, $id ) {
		$data = array(
			'model' => $model,
			'recycled' => $recycled,
			'id' => $id,
		);
		$str = $this->_CI->load->view_part( $this->_site_path.'/site/recycled_button', $data );
	}
	
	
	
	/**
	 * 注册短信接口
	 * $callee 电话号码
	 * $cont 内容
	 */
	public function send_sms_interface( $callee, $cont ) {
		try {
			$this->_CI->config->load( 'phone' );
			//读取配置的用户账号
			$uc = config_item( 'uc' );
			//读取配置的密码
			$pwd = config_item( 'pw' );
			//唯一码
			$msgid = 115;
			//收件人电话
			$callee = $callee;
			//内容
			$cont = iconv( "utf-8", "gbk", $cont );
			$cont = base64_encode( $cont );
			//URL地址
			$services = "http://202.105.212.146:8080/jboss-net/services";
			//注册接口
			$wsdl = "http://202.105.212.146:8080/jboss-net/services/Register?wsdl";
			if ( class_exists( 'SoapClient' ) ) {
				$register = new SoapClient( $wsdl );
			} else {
				$error = "无法创建对象,请开启SOAP扩展";
				throw new Exception( $error );
			}
			//获取随机数
			$reg_rand = $register->GetRandom();
			//加密后密码
			$reg_pw = md5( $reg_rand . $pwd . $pwd );
			//链接通道ID;
			$SetCallback = $register->SetCallbackAddr( $uc, $reg_pw, $reg_rand, $services );
			//第二次取随机数
			$rand = $register->GetRandom();
			//调用sendSMS接口
			$send_wsdl = "http://202.105.212.146:8080/jboss-net/services/SendSMS?wsdl";
			$send_sms = new SoapClient( $send_wsdl, array( 'features' => SOAP_USE_XSI_ARRAY_TYPE ) );
			//执行接口
			$res = $send_sms->sendSMS( $uc, $reg_pw, $rand, $callee, 0, $cont, $msgid, $SetCallback );
			if($res == 0){
				return "ok";
			}
			return $res;
		} catch ( Exception $e ) {
			echo $e->getMessage();
			return false;
		}	
    }

    /*根据系统设置 给用户发邮件、短信
     * $content => array() 需要发送的内容 ，statues =》int 区分是登陆1 还是收发文的通知2  $admin_id =>array 通知用户的id  
     */
    public function by_system_send_message($content,$statues,$admin_id_arr =array()){
        $this->_CI->load->model( 'config_model' );
        $pk_value = 'value';
        if($statues==1){//登陆
          //  $pk1 = 'send_email';
            $pk2 = 'send_sms';
        }else{//收发文
            $pk1 = 'doc_send_email';
            $pk2 = 'doc_send_sms';
        }
        $isset_email = $isset_sms = 0 ;
        $email_content = $this->L($pk1,  $content);//获取需要发送邮件的信息
        $sms_content   = $this->L($pk2 , $content);//需要发送短息的信息
        if( $pk1 ){
           $email_content = $this->L($pk1,  $content);
           $isset_email = $this->_CI->config_model->get_values('key',$pk_value ,array('key'=>$pk1));//获取系统的邮件设置
        }
        if( $pk2 ){
           $email_content = $this->L($pk2,  $content);
           $isset_sms =   $this->_CI->config_model->get_values('key',$pk_value,array('key'=>$pk2));//获取系统的短信设置
        }
        if(isset($isset_email[$pk1])){//发送邮件
            foreach ($admin_id_arr as $admin_id){
                $this->send_mail($admin_id,$email_content);//发送邮件1
            }
         }
        if(isset($isset_sms[$pk2])){//发送短信
            $call_member =  array();
            foreach ($admin_id_arr as $value){
                $call_member[] = $this->_CI->admin_model->get_value_by_pk($value,'phone');//获取这些人的手机号码
            }
            !empty($call_member) && $this->send_sms_interface($call_member, $sms_content);//发送短信
        }
        return true;
    }
  
    /**
	 * 邮件发送
	 * @param  string $message [description]
	 * @return [type]          [description]
	 */
	public function send_mail($admin_id,$message = '') {
        $data = array();
        $email_member = $this->_CI->admin_model->get_by_pk($admin_id);
        $this->_CI->load->library('PHPMailer');
        $mail = new Phpmailer();
        $mail->IsSMTP();
        $this->_CI->config->load('email');
        $mail->SMTPDebug = $this->_CI->config->item('debug');
        $mail->SMTPAuth = $this->_CI->config->item('auth');
        $mail->CharSet = $this->_CI->config->item('charset');
        ;
        $mail->Host = $this->_CI->config->item('host');
        $mail->Port = $this->_CI->config->item('port');
        $mail->Username = $this->_CI->config->item('username');
        $mail->Password = $this->_CI->config->item('password');

        $member_id = $admin_id;
        $body = '<div id="mailContentContainer" class="" style="">
				<br>'.$message.'
				</div>';
        $mail->SetFrom($mail->Username, '深圳市农产品质量安全监测中心后台登陆');
        $mail->AddAddress($email_member['email']);
        $mail->Subject = '登陆验证';
        $mail->AltBody = '';
        $mail->MsgHTML($body);
        if ($mail->Send()) {
            $member = array();
            $ext = explode('@', $email_member['email']);
            $data ['url'] = "http://mail." . $ext[1];
            $data ['is_send'] = TRUE;
            return  $data;
        } else {
            $info = "邮件发送失败";
            $data ['is_send'] = 0;
            return $data;
        }
    }
    
	 /**
	 * 多语言专用-最多为二维数组-替换字符串.str,var,fix为专有关键字,str是指对应的字符串,var是指对应的变量名
	 * 脚本中调用为: L( $lkey, array( 0 => '2009', 1 => 'Jim', 2 => '1000') );
	 * @param string $lkey
	 * @param array $aVar
	 * @param bool $needfind 直接傳字符串進來替換,不需要去語言包裡面尋找
	 * @return string
	 */
	   function L( $lkey, $aVar = array(), $needfind = true ) {
		if( $needfind === true ) {
	                $lang = $this->lang;
	                if(!isset($lang[$lkey])){
	                    return 'language key empty!';
	                }
			$vars = $lang[$lkey];
		} else {
			$vars = $lkey;
		}
	
		if (empty($aVar)) { //没有需要替换的变量,则直接返回
			return $vars;
		}
		foreach ($aVar as $key => $value) {
			$aSearch[] = '#' . $key;
			$aReplace[] = $value;
		}
		return isset( $aSearch ) ? str_replace($aSearch, $aReplace, $vars) : $vars;
	}

	public function get_client_ip() {
		 
		if (getenv("HTTP_CLIENT_IP") && strcasecmp(getenv("HTTP_CLIENT_IP"), "unknown")){
			$ip = getenv("HTTP_CLIENT_IP");
		} else if (getenv("HTTP_X_FORWARDED_FOR") && strcasecmp(getenv("HTTP_X_FORWARDED_FOR"), "unknown")){
			$ip = getenv("HTTP_X_FORWARDED_FOR");
		} else if (getenv("REMOTE_ADDR") && strcasecmp(getenv("REMOTE_ADDR"), "unknown")){
			$ip = getenv("REMOTE_ADDR");
		} else if (isset($_SERVER['REMOTE_ADDR']) && $_SERVER['REMOTE_ADDR'] && strcasecmp($_SERVER['REMOTE_ADDR'], "unknown")){
			$ip = $_SERVER['REMOTE_ADDR'];
		} else {
			$ip = "unknown";
		}
		if(!preg_match('/[\d\.]{7,15}/', $ip)){
			return 'unknown';
		}
		return($ip);
	}
}
